#include "TerrainModel.h"
#include "Texture.h"
#include <string>

using namespace std;

TerrainModel::TerrainModel(Ptr< Terrain > pData,
                           Ptr< ShowListManager > pShowListMng)
{
  _width = pData->width ();
  _height = pData->height ();
  _altitude = pData->altitude ();
  //BuildTexture("TerrainTexture.jpg",textID);
  _build_show_list (pData, pShowListMng);
}


void TerrainModel::draw () const
{
  glCallList (_showListName);
}

void TerrainModel::_build_show_list (Ptr< Terrain > pData,
                                     Ptr< ShowListManager > pShowListMng)
{
  _showListName = pShowListMng->createNewList (GL_COMPILE);
  glEnable( GL_TEXTURE_2D);
  glBindTexture(GL_TEXTURE_2D,textID);

  for (uint y = 0; y < pData->vertexs ().row_num () - 1; ++y)
  {
    glBegin (GL_TRIANGLE_STRIP);
    for (uint x = 0; x < pData->vertexs ().column_num (); ++x)
    {
	  glTexCoord2f((float)x/(float)pData->vertexs().column_num(),(float)y/(float)(pData->vertexs ().row_num () ));
	  glNormal3fv (pData->vertexs ()[y][x].normal ());
      glColor3fv (pData->vertexs ()[y][x].color ());
      glVertex3fv (pData->vertexs ()[y][x].position ());
	  
	  glTexCoord2f((float)x/(float)pData->vertexs().column_num(),(float)(y+1)/(float)(pData->vertexs ().row_num ()));
      glNormal3fv (pData->vertexs ()[y + 1][x].normal ());
      glColor3fv (pData->vertexs ()[y + 1][x].color ());
      glVertex3fv (pData->vertexs ()[y + 1][x].position ());
    }
    glEnd ();
  }

  glEndList ();
}